package org.wat.wcy.isi.mmazur.bp.io.model;

import java.io.IOException;
import java.io.RandomAccessFile;

import org.apache.commons.lang.StringUtils;
import org.wat.wcy.isi.mmazur.bp.io.BinaryObject;

public class IdDesc extends BinaryObject {

	public final static String ID_NULL = "00000000-0000-0000-0000-000000000000";
	private static final int ID_SIZE = ID_NULL.length();
	private static final String ID_REGEX = "[a-zA-Z0-9]{8}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{12}";
	private byte [] data;
	//8,4,4,12 - sum 
	//example: ff403db1-f47c-4f91-becd-597dfa844144
	
	public IdDesc() {
		data = ID_NULL.getBytes();
	}
	
	public IdDesc(String id) {
		if (id == null || id.length() != ID_SIZE) {
			throw new RuntimeException("NmTokenId contructor");
		}
		if (StringUtils.isEmpty(id)) {
			data = ID_NULL.getBytes();
		} else {
			data = id.getBytes(); 
		}
	}
	
	public boolean validate() {
		return new String(data).matches(ID_REGEX);
	}
	
	@Override
	public void write(RandomAccessFile raf) {
		try {
			raf.write(data);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void read(RandomAccessFile raf) {
		try {
			raf.read(data, 0, ID_SIZE);
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	@Override
	public String toString() {
		return new String(data).trim();
	}

	public static int sizeOf() {
		return ID_SIZE;
	}

	public boolean isNull() {
		return StringUtils.equalsIgnoreCase(toString(), ID_NULL);
	}
}
